package controllers

import (
	"github.com/astaxie/beego"
	"html/template"
	"src/gitee.com/wx_e6924dbcd0/notebook/models"
	"strconv"
)

type NoticeMainController struct {
	beego.Controller
}

/**
 * 获取公告列表
 */
//http://127.0.0.1:8080/tmblist
func (c *NoticeMainController) NoticeList() {
	result := make(map[string]interface{})
	NoticeList, err := models.GetNoticeList()
	if err != nil {
		result["Notice"] = "GetNoticeList failed" + err.Error()
		log := models.UitlLog()
		log.Error("GetNoticeList failed", err.Error())
		return
	}
	//获取最新的公告
	NewNotice, err := models.GetNewNotice()
	if err != nil {
		result["Notice"] = "GetNewNotice failed" + err.Error()
		log := models.UitlLog()
		log.Error("GetNewNotice failed", err.Error())
		return
	}
	result["NoticeList"] = NoticeList
	result["NewNotice"] = NewNotice
	c.Data["json"] = result
	c.ServeJSON()
	return
}

/**
 * 上传公告
 */
//http://127.0.0.1:8080/tmbu?user_id=2&message_id=3Do
func (c *NoticeMainController) DoAddNotice() {
	content := template.HTMLEscapeString(c.Input().Get("content"))
	result := make(map[string]interface{})
	// orm insert 存储
	Notice, err := models.AddNotice(content)
	if err != nil {
		result["Notice"] = "AddNotice failed" + err.Error()
		log := models.UitlLog()
		log.Error("AddNotice failed", err.Error())
		return
	} else {
		result["Notice"] = Notice
	}
	c.Data["json"] = result
	c.ServeJSON()
	return
}

/**
 * 根据ID删除公告
 */
//http://127.0.0.1:8080/deltmb?user_id=1&message_id=7
func (c *NoticeMainController) DoDelNotice() {
	// 读取数据库内容
	// 引用model,->orm
	// orm -> 引用 conf 配置连接DB
	// orm 读取数据库
	idStr := template.HTMLEscapeString(c.Input().Get("id"))
	id, erru := strconv.Atoi(idStr)
	if erru != nil {
		log := models.UitlLog()
		log.Error("数据转换 failed", erru.Error())
		return
	}
	result := make(map[string]interface{})
	//执行删除操作
	num, err := models.DelNotice(int64(id))
	if err != nil {
		log := models.UitlLog()
		log.Error("DelNotice failed", err.Error())
		return
	}
	// 成功返回数据
	result["count"] = num
	result["Del"] = "ok"
	c.Data["json"] = result
	c.ServeJSON()
	return
}

/**
 * 置顶公告
 */
//http://127.0.0.1:8080/deltmb?user_id=1&message_id=7
func (c *NoticeMainController) DoUpNotice() {
	// 读取数据库内容
	// 引用model,->orm
	// orm -> 引用 conf 配置连接DB
	// orm 读取数据库
	idStr := template.HTMLEscapeString(c.Input().Get("id"))
	id, erru := strconv.Atoi(idStr)
	if erru != nil {
		log := models.UitlLog()
		log.Error("数据转换 failed", erru.Error())
		return
	}
	result := make(map[string]interface{})
	//执行
	num, err := models.UpNotice(int64(id))
	if err != nil {
		result["count"] = num
		result["UpTmb"] = "UpNotice failed" + err.Error()
		log := models.UitlLog()
		log.Error("UpNotice failed", erru.Error())
		return
	}
	// 成功返回数据
	result["count"] = num
	result["Del"] = "ok"
	c.Data["json"] = result
	c.ServeJSON()
	return
}
